zip解压缩,压缩包里含有中文路径、文件名时由于编码方式的问题而导致报错,通过try:except进行编码测试然后再解压即可,之前看的各种方式。总是在不同环境下各种不同的问题,如py代码编码环境不一样,重写权限问题(有的方式是解压一遍后遍历乱码的解压结果,再重新编码再重新解压,这个会有性能问题),通过下面的方式则不存在性能问题,因为不需要解压两遍。
def zip_decompress(zip_file,path):
try:
zip_dir=os.path.splitext(os.path.basename(zip_file))[0]
zip = zipfile.ZipFile(zip_file, 'r')
if not os.path.isdir(path):
os.makedirs(path)
for each in zip.namelist():
if not each.endswith('/'):
root, name = os.path.split(each)
try:
root = root.encode('cp437').decode('gbk')
except:
root = root.encode('cp437').decode('utf-8')
try:
name = name.encode('cp437').decode('gbk')
except:
name = name.encode('cp437').decode('utf-8')
directory = os.path.normpath(os.path.join(path,zip_dir, root))
if not os.path.isdir(directory):
os.makedirs(directory)
file=open(os.path.join(directory, name), 'wb')
file.write(zip.read(each))
file.close()
zip.close()
except Exception as e:
print (str(e))
|